package Test.xinri;
import biweekly.util.org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dusongsong
 * @date 2023年05月18日 11:33
 */
public class InvokeHelper {

    private final static String URL = "https://apistage.huilianyi.com";
    private final static String CLIENT_ID = "f339304e-3fe4-4f4d-8745-39d8b76db35c";
    private final static String SECURET = "ZjE0NzMzMWUtZjVhOS00ZjVkLWE3NjAtNWNmMWVlZGY0NGQ0";
    public static Map<String,String> map = new HashMap();
    static {
        map.put("ApprovalHistory", "/gateway/api/open/approvalHistory");
        map.put("Pass", "/gateway/api/open/approvals/pass");
        map.put("Reject", "/gateway/api/open/approvals/reject");
    }

    public static void main(String[] args) {
        JSONObject paramJson = new JSONObject();
        paramJson.put("dataflow","泛微oa→RZERPv4_铁建工科");
        paramJson.put("actionCode","put_csxxb");
        JSONArray detailList = new JSONArray();
        JSONObject detailJson = new JSONObject();
        detailJson.put("wbid","123");
        detailJson.put("csjc","asdf");
        detailJson.put("csmc","test");
        detailList.add(detailJson);
        JSONObject dataJson = new JSONObject();
        dataJson.put("Details",detailList);
        JSONObject DataJson = new JSONObject();
        DataJson.put("Data",dataJson);
        paramJson.put("data",DataJson);
        String result = sendOKHttp3Request(paramJson.toJSONString());
        System.out.println(paramJson);
        System.out.println(result);
    }

    public static void testApprovalHistory(){
        JSONObject paramjson = new JSONObject();
        paramjson.put("entityType",1002);
        paramjson.put("entityOID","");
        paramjson.put("businessCode","ER14360774");
        paramjson.put("operationType",1002);
        paramjson.put("operation",2001);
        paramjson.put("operatorOID","");
        paramjson.put("operator","000069");
        paramjson.put("operationDetail","这是审批意见");
        paramjson.put("createdDate","2016-09-18T07:48:59Z");
        paramjson.put("lastModifiedDate","2016-09-18T07:48:59Z");
        String result = approvalHistory(paramjson.toJSONString());
        System.out.println(result);
    }

    public static void testPass(){
        JSONObject paramjson = new JSONObject();
        paramjson.put("approvalTxt","通过");
        paramjson.put("operator","0002");
        paramjson.put("approver","0002");
        paramjson.put("entityType",1002);
        paramjson.put("businessCode","ER14360774");
        String result = pass(paramjson.toJSONString());
        System.out.println(result);
    }

    public static void testReject(){
        JSONObject paramjson = new JSONObject();
        paramjson.put("approvalTxt","不通过");
        paramjson.put("operator","0002");
        paramjson.put("approver","0002");
        paramjson.put("entityType",1002);
        paramjson.put("businessCode","ER14364370");
        String result = reject(paramjson.toJSONString());
        System.out.println(paramjson);
        System.out.println(result);
    }
    /**
     * 获取token
     * @return
     */
    private static String getAccessToken(){
        String tokenUrl = URL+"/oauth/token";
        String authStr = CLIENT_ID.concat(":").concat(SECURET);
        String authStrEnc = new String(Base64.encodeBase64(authStr.getBytes()));
        String accessToken = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("grant_type","client_credentials")
                    .addFormDataPart("scope","write")
                    .build();
            Request request = new Request.Builder()
                    .url(tokenUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Basic ".concat(authStrEnc))
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (!"".equals(result)) {
                JSONObject resultJson = JSONObject.parseObject(result);
                accessToken = resultJson.getString("access_token");
            }
            System.out.println("response="+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 审批历史创建
     * @param content
     * @return
     */
    public static String approvalHistory(String content) {
        return handleHttpPostRequest("ApprovalHistory",content);
    }
    /**
     * 当前审批人审批通过
     * @param content
     * @return
     */
    public static String pass(String content) {
        return handleHttpPostRequest("Pass",content);
    }
    /**
     * 当前审批人审批驳回
     * @param content
     * @return
     */
    public static String reject(String content) {
        return handleHttpPostRequest("Reject",content);
    }

    /**
     * http post请求处理器
     * @param apiType
     * @param params
     * @return
     */
    private static String handleHttpPostRequest(String apiType,String params){
        String result = "";
        String apiUrl = URL+ Util.null2String(map.get(apiType));
        String accessToken = getAccessToken();
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer ".concat(accessToken))
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            result = response.body().string();
        }catch (Exception e) {
            e.printStackTrace();
        }
      return result;
    }

    private static String sendOkHttpRequest(String token,String params){
        String result = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url("https://api.mypiaojia.com/api/invoiceApi/invoice/get?token="+token)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            result = response.body().string();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static String sendOKHttp3Request(String paramJson){
        String result = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, paramJson);
            String url = "http://58.241.13.10:11896/Api/PutData/ExecProcedureWithReturnJsonErrorToBody";
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Accept", "*/*")
                    .build();
            Response response = client.newCall(request).execute();
            result = response.body().string();
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }
}
